package org.voyager.service.wx.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.voyager.service.wx.dao.MpMenuDao;
import org.voyager.service.wx.domain.MpMenuPO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class MpMenuDaoJdbc implements MpMenuDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    final static String Q_ALL = "select id, app_id, menu_type, menu_name, menu_key, url, media_id, page_path, " +
            "enabled, order_seq, parent_id from wechat_menu";

    final static String Q_MENU_BY_ID = "select id, app_id, menu_type, menu_name, menu_key, url, media_id, page_path, " +
            "enabled, order_seq, parent_id from wechat_menu where id = ?";

    @Override
    public List<MpMenuPO> queryAll() {
        return jdbcTemplate.query(Q_ALL, this::menuResultMapper);
    }

    @Override
    public MpMenuPO getMpMenuById(String menuId) {
        return jdbcTemplate.query(Q_MENU_BY_ID,
                new Object[]{menuId},
                this::menuResultMapper).stream().findFirst().orElse(null);
    }

    protected MpMenuPO menuResultMapper(ResultSet rs, int i) throws SQLException {
        MpMenuPO po = new MpMenuPO();
        po.setId(rs.getString("ID"));
        po.setAppId(rs.getString("APP_ID"));
        po.setType(rs.getString("MENU_TYPE"));
        po.setName(rs.getString("MENU_NAME"));
        po.setKey(rs.getString("MENU_KEY"));
        po.setUrl(rs.getString("URL"));
        po.setMediaId(rs.getString("MEDIA_ID"));
        po.setPagePath(rs.getString("PAGE_PATH"));
        po.setEnabled(rs.getBoolean("ENABLED"));
        po.setOrderSeq(rs.getInt("ORDER_SEQ"));
        po.setParentId(rs.getString("PARENT_ID"));
        return po;
    }
}
